package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysUser;
import com.powernode.domain.SysUserRole;
import com.powernode.mapper.SysUserMapper;
import com.powernode.mapper.SysUserRoleMapper;
import com.powernode.service.SysUserRoleService;
import com.powernode.service.SysUserService;
import com.powernode.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    /*
     * 新增管理员
     * @author RenBoQing
     * @date 2024/7/9 21:01
     * @param sysUser
     * @return java.lang.Integer
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        // 新增管理员
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        int insert = sysUserMapper.insert(sysUser);
        if (insert > 0) {
            // 获取管理员标识
            Long userId = sysUser.getUserId();
            if (userId != null) {
                // 获取角色id集合
                List<Long> roleIdList = sysUser.getRoleIdList();
                // 判断是否有角色id集合
                if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() > 0) {
                    //创建管理员角色关联表的集合
                    List<SysUserRole> sysUserRoleList = CollectionUtil.newArrayList();
                    // 遍历角色id集合
                    roleIdList.forEach(roleId -> {
                        // 创建管理员角色关联表
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(userId);
                        sysUserRole.setRoleId(roleId);
                        // 新增关联关系
                        sysUserRoleList.add(sysUserRole);
                    });
                    // 批量新增关联关系 批量操作都在业务层
                    sysUserRoleService.saveBatch(sysUserRoleList);
                }
            }
        }
        return insert;
    }
    /*
     *查询用户的信息
     * @author RenBoQing
     * @date 2024/7/9 22:41
     * @param userId
     * @return com.powernode.domain.SysUser
     */
    @Override
    public SysUser querySysUserInfoByUserId(Long userId) {
        // 根据管理员ID查询管理员详情
        SysUser sysUser = sysUserMapper.selectById(userId);
        // 根据管理员ID查询管理员与角色关系集合
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        if (CollectionUtil.isNotEmpty(sysUserRoleList) && sysUserRoleList.size() > 0) {
            // 获取角色id集合
            List<Long> roleIdList = CollectionUtil.newArrayList();
            // 遍历管理员与角色关系集合
            sysUserRoleList.forEach(sysUserRole -> {
                // 获取角色id
                Long roleId = sysUserRole.getRoleId();
                // 添加到角色id集合
                roleIdList.add(roleId);
            });
            // 设置角色id集合
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }
    /* 1. 删除原有管理员的角色关系  2. 批量新增管理员与角色关系 3.修改管理员的信息
     * 修改管理员 信息
     * @author RenBoQing
     * @date 2024/7/9 22:38
     * @param sysUser
     * @return java.lang.Integer
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer modifySysUser(SysUser sysUser) {
        // 获取管理员ID
        Long userId = sysUser.getUserId();
        // 删除管理员原有的角色
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId)
        );
        // 获取管理员角色id集合
        List<Long> roleIdList = sysUser.getRoleIdList();
        // 判断角色id集合是否有值
        if (CollectionUtil.isNotEmpty(sysUser.getRoleIdList()) && sysUser.getRoleIdList().size() > 0) {
            //创建管理员角色关联表的集合
            //创建管理员角色关联表的集合
            List<SysUserRole> sysUserRoleList = CollectionUtil.newArrayList();
            // 遍历角色id集合
            roleIdList.forEach(roleId -> {
                // 创建管理员角色关联表
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                // 新增关联关系
                sysUserRoleList.add(sysUserRole);
            });
            // 批量新增关联关系 批量操作都在业务层
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        // 修改管理员信息  更新相关信息
        String newPassword = sysUser.getPassword();
        if (StringUtils.hasText(newPassword)) {
            sysUser.setPassword(bCryptPasswordEncoder.encode(newPassword));
        }
        return sysUserMapper.updateById(sysUser);
    }
    /*
     * 删除管理员/批量删除管理员
     * @author RenBoQing
     * @date 2024/7/10 22:58
     * @param userIds
     * @return java.lang.Boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSysUserListByUserIds(List<Long> userIds) {
        if (CollectionUtil.isNotEmpty(userIds) && userIds.size() > 0) {
            // 删除管理员与角色关系
            sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                    .in(SysUserRole::getUserId, userIds)
            );
        }
        // 批量 / 删除管理员
        return sysUserMapper.deleteBatchIds(userIds) ==userIds.size();
    }
}
